package com.tiantianyuegou.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.SetPriceAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.service.UpgradeService;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.view.MyDialogTextView;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 系统设置
 */
public class SetActivity extends BaseActivity implements View.OnClickListener {

    private ImageView img_title;
    private TextView text_title, text_menu;
    private RelativeLayout relative_about_us, relative_use_help, relative_updata;
    private PackageManager mPackageManager;
    private int mVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        findViewByIds();
        initData();
        initListener();
      Tools.changeSystemBar(this);
    }

    public void findViewByIds() {

        img_title = (ImageView) findViewById(R.id.img_title);
        text_title = (TextView) findViewById(R.id.text_title);

        text_title.setText(R.string.set_title);

        relative_about_us = (RelativeLayout) findViewById(R.id.relative_about_us);
        relative_use_help = (RelativeLayout) findViewById(R.id.relative_use_help);
        relative_updata = (RelativeLayout) findViewById(R.id.relative_updata);

    }

    public void initListener() {
        img_title.setOnClickListener(this);
        relative_about_us.setOnClickListener(this);
        relative_use_help.setOnClickListener(this);
        relative_updata.setOnClickListener(this);
    }

    public void initData() {
// 通过包管理器，拿到当前版本的版本号
        mPackageManager = getPackageManager();
        try {
            mVersion = mPackageManager.getPackageInfo(this.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.img_title:
                finish();
                break;

            case R.id.relative_about_us:
                Intent intent1 = new Intent();
                intent1.setClass(SetActivity.this, WebActivity.class);
                intent1.putExtra("type", "3");
                startActivity(intent1);
                break;

            case R.id.relative_use_help:
                Intent intent2 = new Intent();
                intent2.setClass(SetActivity.this, WebActivity.class);
                intent2.putExtra("type", "2");
                startActivity(intent2);
                break;

            case R.id.relative_updata:
                checkVersionUpdate();
                break;

            default:
                break;
        }
    }

    private void checkVersionUpdate() {
        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.setMsg("正在检查新版本中...");
        loadingDialog.show();
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.UPDATE, null, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                loadingDialog.dismiss();
                Log.e("TAG", "check version:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("检查新版本失败");
                } else {
                    try {
                        JSONObject root = new JSONObject(responseInfo.result);
                        String code = root.getString("code");
                        if ("100".equals(code)) {
                            JSONObject info = root.getJSONObject("info");
                            int version = Integer.parseInt(info.getString("tvVersion"));
                            String desp = info.getString("tvDesp");
                            final String url = info.getString("tvUrl");
                            mVersion = 0;
                            if (mVersion < version) {
                                MyDialogTextView dialogTextView = new MyDialogTextView(
                                        SetActivity.this, "有新版本",
                                        desp);
                                dialogTextView.btn_cancel.setText("稍后更新");
                                dialogTextView.btn_confirm.setText("立即更新");
                                dialogTextView.setDialogCallback(new MyDialogTextView.DialogCallback() {
                                    @Override
                                    public void dialogOpt() {
                                        downloadFile(url);
                                    }
                                });
                                dialogTextView.show();
                            } else {
                                showMsg("当前已是最新版本");
                            }
                        } else {
                            String msg = root.getString("message");
                            showMsg(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("解析异常");
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用,请检查您的网络设置");
                Log.e("TAG", "check version failure:" + s);
            }
        });
    }

    /**
     * 开启服务去开始下载任务
     *
     * @param url
     */
    private void downloadFile(String url) {
        Log.e("TAG","url:"+url);
//        url = "http://f.hiphotos.baidu.com/zhidao/wh%3D600%2C800/sign=496abfc08db1cb133e3c3415ed647a76/b7003af33a87e95048e8274310385343fbf2b426.jpg";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
            Intent service = new Intent(this, UpgradeService.class);
            service.putExtra(UpgradeService.INTENT_URL, url);
            startService(service);
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
        }
    }
}
